package org.framework.lazy.cloud.network.heartbeat.protocol.handler;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.socksx.v5.*;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.protocol.auth.NettyPasswordAuth;

@Slf4j
public class NettySocks5PasswordAuthRequestInboundHandler extends SimpleChannelInboundHandler<DefaultSocks5PasswordAuthRequest> {


    private final NettyPasswordAuth nettyPasswordAuth;

    public NettySocks5PasswordAuthRequestInboundHandler(NettyPasswordAuth nettyPasswordAuth) {
        this.nettyPasswordAuth = nettyPasswordAuth;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DefaultSocks5PasswordAuthRequest msg) throws Exception {
        //认证成功

        String username = msg.username();
        String password = msg.password();
        if (nettyPasswordAuth.verify(username, password)) {
            log.debug("login with username:{} password:{}", username, password);
            log.debug("认证直接成功");
            Socks5PasswordAuthResponse passwordAuthResponse = new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS);
            ctx.writeAndFlush(passwordAuthResponse);
            ctx.pipeline().remove(this);
            ctx.pipeline().remove(Socks5PasswordAuthRequestDecoder.class);
        } else {
            log.error("授权失败: with username:{} password:{}", username, password);
            // 认证失败
            Socks5PasswordAuthResponse passwordAuthResponse = new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.FAILURE);
            //发送鉴权失败消息，完成后关闭channel
            ctx.writeAndFlush(passwordAuthResponse).addListener(ChannelFutureListener.CLOSE);
        }

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("处理 SOCKS5 密码认证时发生异常: " + cause.getMessage());
        ctx.close();
    }

}
